<template>
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth - 96 + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary"> 刷新</el-button>
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <el-button @click="addRow" type="primary">增行</el-button>
          <el-button @click="() => openRatify('2', '5', '请确认签批')" type="success">
            签批</el-button
          >
          <el-button @click="deleteSelectedRows" type="danger">删除</el-button>
          <!-- <el-button type="primary" @click="openWorkOrderCode2()" v-if="showInsertButton"
            >测试</el-button
          > -->
          <el-button
            type="primary"
            @click="getAllData(ruleFormRef)"
            v-if="showInsertButton"
            >保存</el-button
          >
          <el-button
            :disabled="isDis"
            type="primary"
            @click="updateMaterialsFixed(ruleFormRef)"
            v-if="!showInsertButton"
            >保存</el-button
          >

          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
      </div>
    </div>

    <div
      ref="titleDiv"
      :style="{
        backgroundColor: 'rgba(247, 247, 247, 0.903)',
        height: 120 + 'px',
        width: screenWidth - 96 + 'px',
      }"
    >
      <el-form :model="formMainTable" :inline="true">
        <el-row :gutter="0">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 工单编码</label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.code"
              disabled
              placeholder="自动添加"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 单据日期 </label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.fdate"
              disabled
              placeholder="自动添加"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              业务人员工号
            </label>
            <el-input
              style="width: 180px"
              v-model="formMainTable.busPersonCode"
              @click="openWorkOrderCode()"
              placeholder="自动添加"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              业务部门名称
            </label>
            <el-input
              style="width: 180px"
              disabled
              v-model="formMainTable.busDeptName"
              placeholder="自动添加"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0" v-if="!isMx">
            <label class="lab" style="width: 100px; padding-right: 5px"> 领回类型</label>
            <el-select
              v-model="formMainTable.ftype"
              style="width: 180px"
              :readonly="true"
              @click="ftypeClick()"
            >
              <el-option label="登记领回" value="0"></el-option>
              <el-option label="磨削领回" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 签批原因 </label>
            <el-input
              style="width: 465px"
              v-model="formMainTable.ratifyExplain"
              :disabled="isRatifyDesc"
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 签批意见 </label>
            <el-input
              style="width: 465px"
              v-model="formMainTable.ratifyDesc"
              :disabled="isRatifyDesc"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px"> 备注 </label>
            <el-input style="width: 1035px" v-model="formMainTable.remarks" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="tableData1"
      stripe
      border
      :row-style="{ height: '20px' }"
      :height="childTableHeight + 'px'"
      style="width: 100%"
      :max-height="childTableHeight + 'px'"
      :cell-style="cellStyle1"
      @selection-change="handleSelectionChange1"
      :header-cell-style="headerCellStyle1"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="行号" width="50" align="center">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="行号" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.rowNum" :style="{ height: '25px' }" />
        </template>
      </el-table-column> -->
      <el-table-column label="单件编号" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input
            @click="openWorkOrderCode1($index)"
            v-model="row.singleCode"
            :style="{ height: '25px' }"
          />
        </template>
      </el-table-column>
      <el-table-column label="最新标准" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.structureName" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <el-table-column label="颜色" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.color" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <el-table-column label="规格" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.specification" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
      <el-table-column label="型号" width="100" align="center">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.modelName" :style="{ height: '25px' }" />
        </template>
      </el-table-column>

      <el-table-column label="备注" align="left">
        <template #header="{ column }">
          <span>
            {{ column.label }}
          </span>
        </template>
        <template #default="{ row, $index }">
          <el-input v-model="row.s_remarks" :style="{ height: '25px' }" />
        </template>
      </el-table-column>

      <el-table-column label="按钮" width="100" align="center">
        <template #default="{ row, $index }">
          <el-button
            :style="{ height: '25px' }"
            type="danger"
            size="mini"
            @click="deleteRow(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="searchButton" type="primary"> 查询</el-button>
          <el-button @click="openInseart" type="success"> 新增</el-button>
          <el-button @click="() => openRatify('2', '5', '请确认签批')" type="success">
            签批</el-button
          >
          <el-button @click="() => openRatify('2', '6', '请确认弃签')" type="success">
            弃签</el-button
          >
          <el-button @click="() => openRatify('1', '3', '请确认审核')" type="warning">
            审核</el-button
          >
          <el-button @click="() => openRatify('1', '4', '请确认弃审')" type="warning">
            弃审</el-button
          >
          <el-button @click="() => openRatify('1', '9', '请确认删除')" type="danger">
            删除</el-button
          >
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;

          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <!-- inputCode -->
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="code"
          placeholder="单据编号"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
        <div class="block">
          <el-date-picker
            v-model="bfdate"
            style="height: 25px; margin-left: 2px; margin-top: 2px"
            type="date"
            placeholder="开始时间"
            size="small"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="block">
          <el-date-picker
            v-model="efdate"
            style="height: 25px; margin-left: 2px; margin-top: 2px"
            type="date"
            placeholder="结束时间"
            size="small"
            value-format="YYYY-MM-DD"
          />
        </div>
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="userName"
          placeholder="业务员名称"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-select
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="state"
          placeholder="状态"
          clearable
          size="small"
        >
          <el-option label="未审核" value="0"></el-option>
          <el-option label="已审核" value="1"></el-option>
        </el-select>
        <el-select
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="isRatify"
          placeholder="是否需要签批"
          clearable
          size="small"
        >
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </el-select>
        <el-select
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="ratifyState"
          placeholder="签批状态"
          clearable
          size="small"
        >
          <el-option label="未签批" value="0"></el-option>
          <el-option label="已签批" value="1"></el-option>
          <el-option label="————————" value="-1"></el-option>
        </el-select>
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="codeSingle"
          placeholder="单据编号(精确)"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row: any) => row.id"
            :max-height="screenHeight"
            :height="screenHeight"
            :max-width="'300px'"
          >
            <el-table-column fixed type="index" width="80" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />

            <el-table-column prop="code" label="单据编号" width="120" align="center" />
            <el-table-column
              prop="fdateInfo"
              label="单据日期"
              width="120"
              align="center"
            />
            <el-table-column
              prop="stateName"
              label="审核状态"
              width="120"
              align="center"
            />
            <el-table-column
              prop="isRatifyName"
              label="是否需要签批"
              width="120"
              align="center"
            />
            <el-table-column
              prop="ratifyStateName"
              label="签批状态"
              width="120"
              align="center"
            />
            <el-table-column
              prop="userName"
              label="业务员名称"
              width="80"
              align="center"
            />
            <el-table-column
              prop="userCode"
              label="业务员工号"
              width="120"
              align="center"
            />
            <el-table-column
              prop="deptName"
              label="部门名称"
              width="120"
              align="center"
            />
            <el-table-column
              prop="createrName"
              label="创建人"
              width="120"
              align="center"
            />
            <el-table-column
              prop="createrDateTime"
              label="创建时间"
              width="200"
              align="center"
            />
            <el-table-column
              prop="modifyName"
              label="修改人"
              width="120"
              align="center"
            />
            <el-table-column
              prop="modifyDateTime"
              label="修改时间"
              width="200"
              align="center"
            />
            <el-table-column
              prop="verifyName"
              label="审核人"
              width="120"
              align="center"
            />
            <el-table-column
              prop="verifyDateTime"
              label="审核时间"
              width="200"
              align="center"
            />
            <el-table-column prop="remarks" label="备注" width="200" align="center" />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
  <SearchTableDialog
    ref="sed"
    @row-data="handleRowData"
    @row-datas="handleRowDatas"
  ></SearchTableDialog>
  <SearchTableDialog1
    ref="sea"
    @row-data="handleRowData1"
    @row-datas="handleRowDatas1"
  ></SearchTableDialog1>
  <SearchTableDialog3
    ref="seb"
    @row-data="handleRowData3"
    @row-datas="handleRowDatas3"
  ></SearchTableDialog3>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../../components/utils/crud.ts";
import * as newCrud from "../../../components/utils/newCrud.ts";

import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import SearchTableDialog1 from "@/components/dialogs/SearchTableDialog1.vue";
import SearchTableDialog3 from "@/components/dialogs/SearchTableDialog3.vue";

import * as notifications from "../../../components/utils/notification.ts";
import Co from "../../../components/utils/t-ui-plus-dev/packages/select-table/src/index.vue";
import moment from "moment";
// 时间
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const tableData = ref([]);
const dialogTableVisible1 = ref(false);
const loading = ref(false);
const page = ref(1);
const limit = ref(50);
const total = ref(50);
// const inputName = ref("");
// const inputCode = ref("");
const code = ref("");
const bfdate = ref("");
const efdate = ref("");
const userName = ref("");
const state = ref("");
const isRatify = ref("");
const ratifyState = ref("");
const codeSingle = ref("");

const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
  code: code.value,
  bfdate: bfdate.value,
  efdate: efdate.value,
  userName: userName.value,
  state: state.value,
  isRatify: isRatify.value,
  ratifyState: ratifyState.value,
  codeSingle: codeSingle.value,
}));
const getUserId = async () => {
  const userName = Cookies.get("userName");
  const res = await crud.fetchData("UserDe/getUserDe", "post", {
    input5: userName,
  });
  console.log(res);
  formMainTableData.value.verifyId = res[0].userId;
  formMainTableData.value.verifyName = res[0].userName;
  formMainTableData.value.ratifyId = res[0].userId;
  formMainTableData.value.ratifyName = res[0].userName;
  formMainTableData.value.ratifyId = res[0].userId;
  formMainTableData.value.ratifyName = res[0].userName;
  formMainTableData.value.createrId = res[0].userId;
  formMainTableData.value.createrName = res[0].userName;
};

const handleSizeChange = (val: number) => {
  selectBusinessType();
};
const handleCurrentChange = (val: number) => {
  selectBusinessType();
};
const searchButton = () => {
  selectBusinessType();
};
const selectBusinessType = async () => {
  await getUserId();
  loading.value = true;
  try {
    const res = await crud.fetchData("/send/getList", "post", selectBusinessDate.value);

    if (res.length == 0) {
      total.value = 0;
      tableData.value = [];
      loading.value = false;
      return;
    }
    tableData.value = res;
    total.value = res[0].total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
selectBusinessType();
// 表格
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const isRatifyDesc = ref(true);
const handleRowClick = async (row, selection) => {
  isDis.value = false;
  if (row.state == 1) {
    isDis.value = true;
  }
  isRatifyDesc.value = false;
  dialogTableVisible1.value = true;
  showInsertButton.value = false;
  isTotalAmount.value = true;

  const res = await crud.fetchData("/send/getListInfo", "post", {
    id: row.id,
  });
  formMainTable.value = { ...formMainTable.value, ...res[0] };
  formMainTable.value.busPersonCode = res[0].userCode;
  formMainTable.value.busDeptName = res[0].deptName;
  const userName = Cookies.get("userName");
  const modifyRes = await crud.fetchData("UserDe/getUserDe", "post", {
    input5: userName,
  });

  formMainTable.value.ftype = modifyRes[0].ftype;
  formMainTable.value.modifyId = modifyRes[0].userId;
  formMainTable.value.modifyName = modifyRes[0].userName;
  tableData1.value = [];
  //   const repairApplicationSubListArray = Object.values(res[0].repairApplicationSubList);
  console.log(res);
  const processedDataArray = res.map((item) => ({
    ...item,
    singleCode: item.uniqueCode,
  }));
  tableData1.value = [...tableData1.value, ...processedDataArray];
  //   tableData1.value = [...tableData1.value, ...repairApplicationSubListArray];

  for (let a = 0; a < 21; a++) {
    addRow();
  }
};

const selectedRows = ref([]);
const table = ref();

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
const screenHeight = ref(null);
const screenWidth = ref(null);
const childTableHeight = ref(null);

const getScreenHeight = () => {
  childTableHeight.value = `${window.innerHeight}` - 203;
  screenHeight.value = window.innerHeight - 146;
  screenWidth.value = window.innerWidth;
};
getScreenHeight();
const formMainTableData = ref({
  verifyId: "",
  verifyName: "",
  ratifyId: "",
  ratifyName: "",
  ratifyDesc: "",
  field_oper_code: "",
  s_oper_code: "",
  idList: "",
});
const field_oper_code = ref("");
const s_oper_code = ref("");
const requestDataAsid = computed(async () => {
  const userName = Cookies.get("userName");
  const res = await crud.fetchData("UserDe/getUserDe", "post", {
    input5: userName,
  });
  formMainTableData.value.verifyId = res[0].userId;
  formMainTableData.value.verifyName = res[0].userName;
  formMainTableData.value.ratifyId = res[0].userId;
  formMainTableData.value.ratifyName = res[0].userName;
  formMainTableData.value.field_oper_code = field_oper_code.value;
  formMainTableData.value.s_oper_code = s_oper_code.value;
  //签批意见
  formMainTableData.value.ratifyDesc = formMainTable.value.ratifyDesc;
  //   const idList = selectedRows.value.map((row) => row.id);
  for (var i = 0; i < selectedRows.value.length; i++) {
    console.log(selectedRows.value[i].id);
  }
  var idList = selectedRows.value.map((row) => row.id).join(",");

  formMainTableData.value.idList = idList;
  return {
    info: formMainTableData.value,
  };
});
const openRatify = async (a, b, c) => {
  try {
    const result = await notifications.showConfirmDialog("", c, "success");

    if (!result) {
      return;
    }
    console.log("selectedRows.value.length:" + selectedRows.value.length);

    if (selectedRows.value.length == 0) {
      notifications.showMessage("请至少选择一行进行操作", "error");
      // notifications.showMessage("xxxxxx", "error");
      return;
    }
    field_oper_code.value = a;
    s_oper_code.value = b;

    const userName = Cookies.get("userName");

    formMainTableData.value.field_oper_code = field_oper_code.value;
    formMainTableData.value.s_oper_code = s_oper_code.value;
    //签批意见
    formMainTableData.value.ratifyDesc = formMainTable.value.ratifyDesc;

    var idList = selectedRows.value.map((row) => row.id).join(",");

    formMainTableData.value.idList = idList;

    //  var requestData = await requestDataAsid.value;

    //  console.log("requestData:" + JSON.stringify(requestData));
    console.log("formMainTableData:" + JSON.stringify(formMainTableData.value));

    const res = await newCrud.sendRequest("/send/send_back_state_update", "post", {
      info: formMainTableData.value,
    });

    selectedRows.value = [];
    selectBusinessType();
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getParentIds = (nodeId) => {
  const parentIds = [];
  let currentNode = asideListData.value.find((node) => node.id === nodeId);
  while (currentNode && currentNode.parentID !== null) {
    parentIds.push(currentNode.id);
    currentNode = asideListData.value.find((node) => node.id === currentNode.parentID);
  }
  return parentIds.reverse();
};

// 新增页面展示
const openInseart = async () => {
  isRatifyDesc.value = true;
  const userName = Cookies.get("userName");
  const res = await crud.fetchData("UserDe/getUserDe", "post", {
    input5: userName,
  });
  formMainTable.value.busDeptName = res[0].deptName;
  formMainTable.value.busPersonCode = res[0].userCode;
  formMainTable.value.busPerson = res[0].userId;
  formMainTable.value.busDept = res[0].deptID;
  formMainTable.value.createrId = res[0].userId;
  formMainTable.value.createrName = res[0].userName;
  isTotalAmount.value = false;
  dialogTableVisible1.value = true;
  showInsertButton.value = true;
  isRepairApplication.value = false;
  nextTick(() => {
    for (let a = 0; a < 21; a++) {
      addRow();
    }
  });
};

interface RuleForm {
  id: string;
  workOrderCode: string;
  grindingProcessStandard: string;
  supplier: string;
  status: true;
  supplierAddress: string;
}
const form = reactive<RuleForm>({
  id: "",
  workOrderCode: "",
  grindingProcessStandard: "",
  supplier: "",
  supplierAddress: "",
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  // name: [{ message: "请输入班组名称", trigger: "blur"  }],
});
// 子表展示
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};
const showInsertButton = ref(true);
const multipleTableRef = ref();
const handleSelectionChange1 = (val: any[]) => {};
const handleInput = (prop) => {
  const val = parseFloat(formMainTable.value[prop]);
  if (!isNaN(val) && isFinite(val)) {
    //  const roundedVal = val.toFixed(4);
    const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
    formMainTable.value[prop] = roundedVal;
    return;
  }
  formMainTable.value[prop] = 0;
};
const handleInput1 = (row, index, prop) => {
  const val = parseFloat(row[prop]);
  if (!isNaN(val) && isFinite(val)) {
    //  const roundedVal = val.toFixed(4);
    const roundedVal = val.toString().match(/^-?\d+(\.\d{0,4})?/)[0];
    row[prop] = roundedVal;
    return;
  }
  row[prop] = 0;
};
const defaultRowData = {
  id: "",
  singleCode: "", //单件编号
  singleId: "", //单价id
  lastPT: "", //最新标准id
  structureName: "", //最新标准
  color: "", //颜色
  specification: "", //规格
  modelName: "", //型号
  s_remarks: "", //备注
};

const tableData1 = ref([
  {
    ...defaultRowData,
  },
  // More data...
]);

const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
  selectBusinessType();
  flushed();
  //   clearForm();
};
// const clearForm = () => {
//   Object.keys(form).forEach((key) => {
//     if (typeof form[key] === "boolean") {
//       Vue.set(form, key, true);
//     } else {
//       Vue.set(form, key, "");
//     }
//   });
// };

const flushed = () => {
  Object.keys(formMainTable.value).forEach((key) => {
    formMainTable.value[key] = "";
  });
  formMainTable.value.ftype = "1";
  tableData1.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
const addRow = () => {
  tableData1.value.push({ ...defaultRowData });
};
const requestFormTable = computed(() => {
  const usefulDataArray = tableData1.value.filter(
    (item) =>
      item.singleCode !== "" &&
      item.singleCode !== "undefined" &&
      item.singleCode !== null
  );

  const formMainTableDate = formMainTable.value;
  const userName = Cookies.get("userName");
  //   const creationTime: creationTime = getCurrentFormattedDateTime();
  const timestamp = new Date().getTime();
  return {
    userName: userName,
    time: timestamp,
    childList: usefulDataArray,
    formMainTable: formMainTableDate,
  };
});
//必填验证
const isTrue = ref(true);
const isRole = () => {
  isTrue.value = true;
  if (requestFormTable.value.childList.length == 0) {
    notifications.showMessage("请选择单件", "error");
    return;
  }
  isTrue.value = false;
};

const requestFormTable1 = computed(() => {
  const usefulDataArray = tableData1.value.filter(
    (item) =>
      item.singleCode !== "" &&
      item.singleCode !== "undefined" &&
      item.singleCode !== null
  );

  const formMainTableDate = formMainTable.value;
  const userName = Cookies.get("userName");
  const timestamp = new Date().getTime();
  const fdate = moment(timestamp).format("YYYY-MM-DD HH:mm:ss");

  const jsonObj = {
    //  userName: userName,
    //  time: timestamp,
    info: formMainTableDate,
    entity: usefulDataArray,
  };
  jsonObj.info["userName"] = userName;
  jsonObj.info["fdate"] = fdate;

  return jsonObj;
});
const updateMaterialsFixed = async () => {
  try {
    await isRole();
    if (isTrue.value) {
      return;
    }

    const result = await notifications.showConfirmDialog("", "请确认保存", "success");

    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }

    const res = await newCrud.sendRequest(
      "/send/upDate",
      "post",
      requestFormTable1.value
    );

    if (res.code == 200 || res.code == 1) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getAllData = async () => {
  try {
    if (!date || isNaN(date.getTime())) {
      // 如果日期为空或无效，返回空字符串或默认值
      return "";
    }
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    await isRole();
    if (isTrue.value) {
      return;
    }

    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }

    const res = await newCrud.sendRequest("/send/insert", "post", requestFormTable.value);
    if (res.code == 200 || res.code == 1) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getSelectedData = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
};

const deleteSelectedRows = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  selectedRows.forEach((row) => {
    const index = tableData1.value.indexOf(row);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
    }
  });
};

const deleteRow = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index !== -1) {
    tableData1.value.splice(index, 1);
  }
};
const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "bold",
  color: "#1F2129",
  height: "40px",
  margin: 0,
  padding: 0,
  textAlign: "center",
};
// 弹窗
const indexEmployeeJob = ref(0);
const isRepairApplication = ref(false);
const isdisRepairApplication = ref(false);
const isTotalAmount = ref(true);
const flushed1 = async (value) => {
  formMainTable.value.workTeam = "";
  formMainTable.value.name = "";
  formMainTable.value.repairTime = "";
  formMainTable.value.repairTimeUnit = "";
  formMainTable.value.supplier = "";
  formMainTable.value.supplierAddress = "";
};
const handleValueRangeChange = async (value) => {
  flushed1();
  let repairMode = formMainTable.value.repairMode;
  if (repairMode == "0") {
    isRepairApplication.value = false;
    isdisRepairApplication.value = false;
  } else {
    isRepairApplication.value = true;
    isdisRepairApplication.value = true;
  }
};
const sed = ref<any>(null);
const sea = ref<any>(null);
const seb = ref<any>(null);

const openWorkOrderCode = async () => {
  sed.value.dialogTableVisible = true;
  await openDial();
};
const openWorkOrderCode1 = async () => {
  sea.value.dialogTableVisible = true;
  await openDial1();
};
const openWorkOrderCode2 = async () => {
  seb.value.dialogTableVisible = true;
  await openDial2();
};
const tableDemo = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  { prop: "userCode", label: "业务员工号", width: "150", align: "center" },
  { prop: "userName", label: "业务员名称", width: "150", align: "center" },
  { prop: "deptCode", label: "部门编号", width: "150", align: "center" },
  { prop: "deptName", label: "部门名称", width: "150", align: "center" },
  { prop: "description", label: "说明", width: "150", align: "center" },
]);
const tableDemo1 = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  { prop: "uniqueCode", label: "单件编号", width: "150", align: "center" },
  { prop: "ecsName", label: "零件名称", width: "150", align: "center" },
  { prop: "modelName", label: "型号", width: "100", align: "center" },
  { prop: "specification", label: "规格", width: "100", align: "center" },
  { prop: "processName", label: "标准名称", width: "300", align: "center" },
  { prop: "color", label: "颜色", width: "150", align: "center" },
]);
const openDial = () => {
  sed.value.ifRowChoose = false;
  sed.value.ifdynamic1 = true;
  sed.value.dynamicPlaceholder1 = "业务员工号";
  sed.value.ifdynamic2 = true;
  sed.value.dynamicPlaceholder2 = "业务员名称";
  sed.value.ifdynamic3 = true;
  sed.value.dynamicPlaceholder3 = "部门编号";
  sed.value.ifdynamic3 = true;
  sed.value.dynamicPlaceholder4 = "部门名称";
  sed.value.ifdynamic4 = true;
  sed.value.tableColumns = tableDemo.value;
  sed.value.compareValue = "userId";
  sed.value.apiUrl = "UserDe/getUserDe";
  sed.value.searchInput();
};
const openDial1 = () => {
  sea.value.ifRowChoose = true;
  sea.value.ifdynamic1 = true;
  sea.value.dynamicPlaceholder1 = "零件名称";
  sea.value.ifdynamic2 = true;
  sea.value.dynamicPlaceholder2 = "结构名称";
  sea.value.ifdynamic3 = true;
  sea.value.dynamicPlaceholder3 = "型号";
  sea.value.ifdynamic3 = true;
  sea.value.dynamicPlaceholder4 = "唯一码";
  sea.value.ifdynamic4 = true;
  sea.value.ifdynamic6 = false;
  sea.value.input6 = formMainTable.value.ftype;
  sea.value.tableColumns = tableDemo1.value;
  //   sea.value.inputParams = [
  //     "escName",
  //     "structureName",
  //     "modelName",
  //     "uniqueCode",
  //     "input5",
  //     "inputParams",
  //   ];
  sea.value.apiUrl = "/send/getPartSingleRegister";
  sea.value.searchInput();
};
const openDial2 = () => {
  if (!seb.value) return;

  // 设置多选
  seb.value.ifRowChoose = true;

  // 设置动态占位符
  seb.value.dynamicPlaceholders = [
    "单件编号",
    "型号",
    "零件名称",
    "结构名称",
    "单件精确",
    "快速检索码",
    "工单类型",
  ];

  // 设置是否显示输入框
  seb.value.ifdynamic = [true, true, true, true, true, true, true, false];

  // 设置第七个输入框的默认值
  seb.value.inputParams.input7 = formMainTable.value.ftype;

  // 设置表格列
  seb.value.tableColumns = tableDemo1.value;

  // 设置输入参数名称
  seb.value.inputParams = {
    input1: ref(""),
    input2: ref(""),
    input3: ref(""),
    input4: ref(""),
    input5: ref(""),
    input6: ref(""),
    input7: ref(formMainTable.value.ftype),
    input8: ref(""),
  };

  // 设置API URL
  seb.value.apiUrl = "/WOP/getPars";

  // 调用搜索方法
  seb.value.searchInput();
};
// const flushed1 = () => {
//   tableData1.value = [];
//   for (let a = 0; a < 21; a++) {
//     addRow();
//   }
// };

const handleRowData = async (row) => {
  formMainTable.value.busDeptName = row.deptName;
  formMainTable.value.busPersonCode = row.userCode;
  formMainTable.value.busPerson = row.userId;
  formMainTable.value.busDept = row.deptID;
};

const handleRowDatas = (row) => {};
const handleRowDatas1 = (row) => {
  const rowLength = row.length;

  if (rowLength == 0) {
    return;
  }
  addRow();
  for (let k = 0; k < row.length; k++) {
    for (let i = 0; i < tableData1.value.length; i++) {
      if (tableData1.value[i].singleCode == row[k].unique_code) {
        notifications.showMessage("第" + (i + 1) + "行单件唯一码重复", "error");
        return;
      }
    }
  }

  for (let i = 0; i < tableData1.value.length; i++) {
    if (
      tableData1.value[i].singleCode == "" ||
      tableData1.value[i].singleCode == undefined
    ) {
      for (let k = 0; k < row.length; k++) {
        tableData1.value[i + k].singleCode = row[k].uniqueCode;
        tableData1.value[i + k].structureName = row[k].structureName;
        tableData1.value[i + k].color = row[k].color;
        tableData1.value[i + k].specification = row[k].specification;
        tableData1.value[i + k].modelName = row[k].modelName;
        tableData1.value[i + k].s_remarks = row[k].s_remarks;
        tableData1.value[i + k].singleId = row[k].id;
        tableData1.value[i + k].lastPT = row[k].lastPT;
      }

      return;
    }
    // 将内部循环后的代码移到这里
    // 检查是否与现有的唯一码匹配
  }
};
const handleRowDatas3 = (row) => {
  const rowLength = row.length;

  if (rowLength == 0) {
    return;
  }
  addRow();
  for (let k = 0; k < row.length; k++) {
    if (tableData1.value[k].singleCode === row[k].uniqueCode) {
      // Show a warning or handle the duplicate here
      notifications.showMessage("第" + (k + 1) + "行单件编号重复", "error");
      return;
    }
  }
  for (let i = 0; i < tableData1.value.length; i++) {
    if (
      tableData1.value[i].singleCode == "" ||
      tableData1.value[i].singleCode == undefined
    ) {
      for (let k = 0; k < row.length; k++) {
        tableData1.value[i + k].singleCode = row[k].uniqueCode;
        tableData1.value[i + k].structureName = row[k].structureName;
        tableData1.value[i + k].color = row[k].color;
        tableData1.value[i + k].specification = row[k].specification;
        tableData1.value[i + k].modelName = row[k].modelName;
        tableData1.value[i + k].s_remarks = row[k].s_remarks;
        tableData1.value[i + k].singleId = row[k].id;
        tableData1.value[i + k].lastPT = row[k].lastPT;
      }

      return;
    }
    // 将内部循环后的代码移到这里
    // 检查是否与现有的唯一码匹配
  }
};
const findLevelByValue = (options, targetValue) => {
  for (const option of options) {
    // 如果当前选项的值与目标值匹配，则返回该选项的级别
    if (option.value === targetValue) {
      return option.label;
    }
    // 如果当前选项有子选项，则递归调用该函数
    if (option.children && option.children.length > 0) {
      const label = findLevelByValue(option.children, targetValue);
      // 如果在子选项中找到了目标值，则返回找到的级别
      if (label !== undefined) {
        return label;
      }
    }
  }
  // 如果未找到目标值，则返回 undefined
  return undefined;
};
// const handleChange = (value) => {
//   const selectedValue = value[value.length - 1];
//   form.businessTypeID = selectedValue;
//   const label = findLevelByValue(parentIDOptions.value, selectedValue);
//   form.businessTypeName = label;
// };

// 查询下拉框;
// 组织类型
const options = reactive([
  {
    value: "Option1",
    label: "Option1",
  },
]);

const transformResToOptions = (res) => {
  return res.map((item) => {
    return {
      value: item.code,
      label: item.codeName,
    };
  });
};

// 定义前端数据模型
const formMainTable = ref({
  autoid: "",
  ID: "",
  code: "", // 单据编号
  fdate: "", // 单据日期
  busPerson: "", // 业务人员
  busPersonCode: "", //业务人员工号
  busDept: "", // 业务部门
  busDeptName: "", // 业务部门名称
  ftype: "1", //领回类型,
  state: "0", // 单据状态
  isRatify: "0", // 是否需要签批
  ratifyState: "0", // 签批状态
  ratifyExplain: "", // 签批原因
  ratifyDesc: "", // 签批意见
  createrName: "", // 制单人名称
  createrId: "", // 制单人
  createrDateTime: "", // 制单时间
  modifyName: "", // 修改人名称
  modifyId: "", // "",
  modifyDateTime: "", // 修改时间
  verifyName: "", // 审核人名称
  verifyId: "", // 审核人
  verifyDateTime: "", // 审核时间
  remarks: "", // 备注
});

const dynamicTitle = ref("展开参数");

const handleChange = (val: string[]) => {
  if (dynamicTitle.value == "折叠参数") {
    dynamicTitle.value = "展开参数";
    //  scollbarHeight.value = 724;
    childTableHeight.value = `${window.innerHeight}` - 252;
    collapsed.value = 48;
    return;
  }
  dynamicTitle.value = "折叠参数";
  //   affixOffset.value = 500;
  //   scollbarHeight.value = 472;
  childTableHeight.value = `${window.innerHeight}` - 513;
  collapsed.value = 300;
  return;
};
//下拉表格
const selectTable = ref();
const stateTable: any = reactive({
  table: {
    total: 0,
    currentPage: 1,
    data: [],
    columns: [
      { prop: "uniqueCode", label: "单件唯一码", width: "150", align: "center" },
      { prop: "equipmentName", label: "设备名称", width: "150", align: "center" },
      {
        prop: "materialCode",
        label: "物料编码",
        width: "150",
        align: "center",
      },
      { prop: "material", label: "材质", width: "150", align: "center" },
      { prop: "specification", label: "规格", width: "150", align: "center" },
      { prop: "model", label: "型号", width: "150", align: "center" },
    ],
  },
});
onMounted(() => {
  getData(1);
});

const uniqueCode = ref("");
const getData = async (pageNum) => {
  const res = await crud.fetchData("/Rep/select/OutsourcingResultList", "post", {
    page: pageNum,
    limit: 1000,
    input2: uniqueCode.value,
  });
  if (res.length == 0) {
    stateTable.table.total = 0;
    stateTable.table.data = [];

    return;
  }
  stateTable.table.data = res;
  stateTable.table.total = res[0].total;
};
// 获取当前的页码
const pageChange = (val) => {
  stateTable.table.currentPage = val;
  getData(val);
};
const handleStatusChange = (row) => {
  let text = row.enableStatus === 1 ? "启用" : "废止";
  ElMessageBox.confirm(`确认要${text}这条数据吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("点击确定");
    })
    .catch(() => {
      console.log("点击取消");
    });
};
const radioChange = async (row) => {
  if (Object.keys(row).length === 0) {
    return;
  }
  addRow();
  for (let i = 0; i < tableData1.value.length; i++) {
    if (
      tableData1.value[i].uniqueCode == "" ||
      tableData1.value[i].uniqueCode == undefined
    ) {
      tableData1.value[i].componentId = row.componentId;
      tableData1.value[i].equipmentStructureId = row.equipmentStructureId;
      tableData1.value[i].material = row.material;
      tableData1.value[i].specification = row.specification;
      tableData1.value[i].model = row.model;
      tableData1.value[i].uniqueCode = row.uniqueCode;

      return;
    } else if (tableData1.value[i].uniqueCode === row.uniqueCode) {
      // Show a warning or handle the duplicate here
      notifications.showMessage("第" + (i + 1) + "单件唯一码重复", "error");
      return;
    }
  }

  selectTable.value.clear();
};
const filterMethod = async (val) => {
  uniqueCode.value = val;
  getData(stateTable.table.currentPage);
};
const handleBlurTable = () => {
  selectTable.value.clear();
};
const rowState1 = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
  };
};
const ftypeClick = () => {
  tableData1.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
</style>
